package base.thread.waitNotify;

import java.util.HashMap;
import java.util.concurrent.Semaphore;

/**
 * Semaphore
 * 使用场景：8个工人公用3台机器
 */
public class SemaphoreDemo {



    static class Work implements Runnable{

        HashMap<String,String >hashMap=new HashMap<>();

        private  int workNum;
        private  Semaphore semaphore;
        //使用场景：8个工人公用3台机器

        public Work(int workNum, Semaphore semaphore){
            this.workNum=workNum;
            this.semaphore=semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                String name=Thread.currentThread().getName();
                System.out.println(name+"  working ..");
                Thread.sleep(100);
                semaphore.release();
                System.out.println(name+" work  is over  release");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int works=8;//8个工人
        Semaphore semaphore=new Semaphore(3);//代表3台机器
        for (int i=0;i<works;i++){
            new Thread(new Work(i,semaphore),"工人"+i).start();
        }
    }



}
